<template>
	<view class="menu-box left clearfix">
		<view class="menu-breadcrumb left clearfix">
			<uni-breadcrumb separator="/" style="width:300px;float:left;">
			  <uni-breadcrumb-item v-for="(route,index) in routes" :key="index" :to="route.to">
			    {{route.name}}
			  </uni-breadcrumb-item>
			</uni-breadcrumb>
			
		</view>
		
		<!--内容开始-->
		<view class="add-box left clearfix">
			<uni-section title="商品编辑" type="line">
				<view class="example">
					<!-- 基础用法，不包含校验规则 -->
					<uni-forms ref="form" :modelValue="formData" label-width="120">
						
						<uni-forms-item label="商品名称" required name="title">
							<uni-easyinput v-model="formData.title" placeholder="商品名称，格式：中文名称|英文名称，如：光束导轨|Optical Rails，120个汉字以内" />
						</uni-forms-item>
						
						<uni-forms-item label="商品分类" required name="category">
							<uni-data-picker placeholder="请选择分类" v-model="categoryVal" popup-title="请选择商品分类" :localdata="category" @change="onchangeCategory">
										</uni-data-picker>
						</uni-forms-item>
						
						
						<uni-forms-item label="商品介绍" required name="content">
							<textarea v-model="formData.content" maxlength="20000" placeholder="格式为：中文介绍|英文介绍，如：这是一个非常好的产品|this is a very good product"></textarea>
						</uni-forms-item>
						<uni-forms-item label="商品特色" required name="feature">
							<textarea v-model="feature" maxlength="20000" placeholder="格式为：中文特色|英文特色@中文特色2|英文特色2，最多10条，每条40个汉字以内"></textarea>
						</uni-forms-item>
						<uni-forms-item label="封面图（中文)" required name="poster">
							<div class="goods-poster left" @click="uploadPoster('zh')" v-if="!formData.poster">
								<div>
									<uni-icons type="icon-jia15" size="50" custom-prefix="iconfont" color="#00c296" ></uni-icons>
								</div>
								<div v-if="uploadItem!='poster' || percent==0">只支持jpg,webp格式，尺寸为1920*540，大小不能超过5M。</div>
								<div v-if="uploadItem=='poster' && percent > 0" style="margin-top:100px;">
								<progress :percent="percent" show-info stroke-width="3" />
								</div>
							</div>
							
							<div class="goods-poster left" @click="uploadPoster('zh')" v-if="formData.poster">
								<image :src="formData.poster" mode="aspectFill" style="width:100%;height:100%;"></image>
							</div>
							
						</uni-forms-item>
						
						<uni-forms-item label="封面图（英文）" required name="en_poster">
							<div class="goods-poster left" @click="uploadPoster('en')" v-if="!formData.en_poster">
								<div>
									<uni-icons type="icon-jia15" size="50" custom-prefix="iconfont" color="#00c296" ></uni-icons>
								</div>
								<div v-if="uploadItem!='en_poster' || percent==0">只支持jpg,webp格式，尺寸为1920*540，大小不能超过5M。</div>
								<div v-if="uploadItem=='en_poster' && percent > 0" style="margin-top:100px;">
								<progress :percent="percent" show-info stroke-width="3" />
								</div>
							</div>
							
							<div class="goods-poster left" @click="uploadPoster('en')" v-if="formData.en_poster">
								<image :src="formData.en_poster" mode="aspectFill" style="width:100%;height:100%;"></image>
							</div>
							
						</uni-forms-item>
						
						
						
						
						
						<uni-forms-item label="主图（中文）" required name="images">
							<uni-file-picker 
								v-model="formData.images" 
								fileMediatype="image" 
								mode="grid" 
								limit="10"
								:image-styles="{width:'150px',height:'150px'}"
								@success="success"
								@fail="fail"
							/>
							<div style="line-height:40px;color:#999;">只支持jpg格式，尺寸800px * 800px,大小不超过5M，最多10张。</div>
						</uni-forms-item>
						
						<uni-forms-item label="主图（英文）" required name="en_images">
							<uni-file-picker 
								v-model="formData.en_images"
								fileMediatype="image" 
								mode="grid" 
								limit="10"
								:image-styles="{width:'150px',height:'150px'}"
								@success="success"
								@fail="fail"
							/>
							<div style="line-height:40px;color:#999;">只支持jpg格式，尺寸800px * 800px,大小不超过5M，最多10张。</div>
						</uni-forms-item>
						
						
						<uni-forms-item label="参数规格（中文）" name="spec">
							<zmt-editor @contentChange="getZhSpec" :initialContent="spec" ></zmt-editor>
						</uni-forms-item>
						
						<uni-forms-item label="参数规格（英文）" name="en_spec">
							<zmt-editor  @contentChange="getEnSpec" :initialContent="en_spec"></zmt-editor>
						</uni-forms-item>
						
						
						<uni-forms-item label="技术说明（中文）" name="describe">
							<zmt-editor @contentChange="getZhDescribe" :initialContent="describe"></zmt-editor>
						</uni-forms-item>
						
						<uni-forms-item label="技术说明（英文）" name="en_describe">
							<zmt-editor @contentChange="getEnDescribe" :initialContent="en_describe"></zmt-editor>
						</uni-forms-item>
						
						<!-- <uni-forms-item label="使用说明图（中文）" name="describe_image">
							<uni-file-picker 
								v-model="formData.describe_image" 
								fileMediatype="image" 
								mode="grid" 
								limit="1"
								:image-styles="{width:'150px',height:'150px'}"
								@success="success"
								@fail="fail"
							/>
							<div style="line-height:40px;color:#999;">只支持jpg格式，尺寸500px * 500px</div>
						</uni-forms-item> -->
						
						<!-- <uni-forms-item label="使用说明图（英文）" name="en_describe_image">
							<uni-file-picker 
								v-model="formData.en_describe_image"
								fileMediatype="image"
								mode="grid"
								limit="1"
								:image-styles="{width:'150px',height:'150px'}"
								@success="success"
								@fail="fail"
							/>
							<div style="line-height:40px;color:#999;">只支持jpg格式，尺寸500px * 500px</div>
						</uni-forms-item> -->
						
						
						<uni-forms-item label="应用举例（中文）" name="example_image">
							<uni-file-picker 
								v-model="formData.example_image"
								fileMediatype="image"
								mode="grid" 
								limit="10"
								:image-styles="{width:'150px',height:'150px'}"
								@success="success"
								@fail="fail"
							/>
							<div style="line-height:40px;color:#999;">只支持jpg格式，最大尺寸800px * 800px,最多10张</div>
						</uni-forms-item>
						
						<uni-forms-item label="应用举例（英文）" name="en_example_image">
							<uni-file-picker 
								v-model="formData.en_example_image" 
								fileMediatype="image" 
								mode="grid" 
								limit="10"
								:image-styles="{width:'150px',height:'150px'}"
								@success="success"
								@fail="fail"
							/>
							<div style="line-height:40px;color:#999;">只支持jpg格式，最大尺寸800px * 800px,最多10张</div>
						</uni-forms-item>
						
						
						<uni-forms-item label="3D模型" name="mode">
							<uni-file-picker
								v-model="formData.step_file" 
								fileMediatype="all"
								mode="grid"
								limit="10"
								:image-styles="{width:'150px',height:'150px'}"
								@success="uploadStepSuccess"
								@fail="fail"
								file-extname="glb"
							/>
							<div style="line-height:40px;color:#999;">glb格式文档</div>
						</uni-forms-item>
						
						<uni-forms-item label="型号参数" name="param">
							<!--属性设置-->
							<view class="param-boxs left clearfix">
								
								<view class="param-trss left clearfix" v-for="(item,index) in param" style="margin-top:20px;">
									<view class="param-tr left clearfix relative" >
										<view class="param-td left">
											型号
										</view>
										<view class="param-td left">
											编号
										</view>
										<view class="param-td left">
											规格|specs
										</view>
										<view class="param-td left">
											单价|price
										</view>
										<view class="param-td left" style="border-right:none;">
											发货日期|delivery time
										</view>
										
										<!--删除按钮-->
										<view class="param-del-icon right absolute" title="删除该项" @click="delParam(index)">
											<uni-icons type="closeempty" size="18" color="#666"></uni-icons>
										</view>
									</view>
								
								
									<view class="param-trs left clearfix">
										<view class="param-td left">
											<input placeholder="中文|英文" v-model="param[index].model">
										</view>
										<view class="param-td left">
											<input placeholder="中文|英文" v-model="param[index].serial_number">
										</view>
										<view class="param-td left">
											<input placeholder="中文|英文" v-model="param[index].spec">
										</view>
										<view class="param-td left">
											<input placeholder="中文|英文"  v-model="param[index].price">
										</view>
										<view class="param-td left" style="border-right:none;">
											<uni-data-select
												  v-model="param[index].en_delivery_time"
												  :localdata="deliveryTime"
												  @change="changeDeliveryTime"
												></uni-data-select>
										</view>
										
									</view>
									
									<!--富文本开始-->
									<view class="param-fuwenben left clearfix">
										<textarea v-model="param[index].children" maxlength="20000"  placeholder="请输入属性，格式：中文属性：中文属性值@英文属性：英文属性值#中文属性2：中文属性值2@英文属性2：英文属性值2"></textarea>
									</view>
									<!--富文本结束-->
									 
									<view class="param-tr left clearfix" style="background:none;border-top:1px solid #eee;border-bottom:1px solid #eee;margin-bottom:20px;">
										<view class="param-td left"  @click="uploadParamImage(index)">
											<label style="border:none;background:none;width:40px;height:40px;float:left;" v-if="param[index].image">
												<image :src="param[index].image" mode="aspectFill" style="width:30px;height:30px;border-radius: 5px;border:1px solid #ccc;margin-top:-2px;"></image>
											</label>
											<label v-if="!param[index].image">上传主图</label>
											<label v-else style="color:#00c296;">
												已上传
											</label>
										</view>
										
										<view class="param-td left" @click="uploadFile('zhpdf',index)">
											<label v-if="!param[index].zh_pdf || !param[index].zh_pdf.url">上传中文PDF文档</label>
											<label v-else style="color:#00c296;">已上传</label>
										</view>
										<view class="param-td left" @click="uploadFile('enpdf',index)">
											<label v-if="!param[index].en_pdf  || !param[index].en_pdf.url">上传英文PDF文档</label>
											<label v-else style="color:#00c296;">已上传</label>
										</view>
										<view class="param-td left" @click="uploadFile('zh3d',index)">
											<label v-if="!param[index].zh_3d || !param[index].zh_3d.url">上传中文3D文档</label>
											<label v-else style="color:#00c296;">已上传</label>
										</view>
										<view class="param-td left" style="border-right:none;"  @click="uploadFile('en3d',index)">
											<label v-if="!param[index].en_3d || !param[index].en_3d.url">上传英文3D文档</label>
											<label v-else style="color:#00c296;">已上传</label>
										</view>
										
									</view>
									
								</view>
								
								
								
							</view>
							<view class="param-more-add left clearfix" @click="addParam()">
								增加一项
							</view>
						</uni-forms-item>
						
						
						
						
						
						<uni-forms-item label="是否上架" required name="is_shelf">
							<switch @change="setIsshow" :checked="formData.is_shelf" style="margin-top:5px;" />
						</uni-forms-item>
						
						<uni-forms-item label="" style="margin-top:50px;text-align: center;">
							
							<view class="form-quxiao-submit right" @click="navigatorToList()">
								取消
							</view>
							
							<view class="form-submit right" @click="submitForm">
								确定
							</view>
							
						</uni-forms-item>
						
					</uni-forms>
				</view>
			</uni-section>
			
		</view>
		<!--内容结束-->
		
	</view>
</template>
<style>
	.uni-select {
	    font-size: 14px;
	    border: 1px solid #fff !important;
	    box-sizing: border-box;
	    border-radius: 4px;
	    padding: 2px 5px !important;
	    padding-left: 10px;
	    position: relative;
	    display: flex;
	    -webkit-user-select: none;
	    user-select: none;
	    flex-direction: row;
	    align-items: center;
	    border-bottom: solid 1px #fff !important;
	    width: 100%;
	    flex: 1;
	    height: 40px !important; 
	}
	.goods-label:hover{background:#2979ff;color:#fff;}
	.goods-label{padding:3px 10px;background:#efefef;border-radius: 3px;margin-right:5px;color:#666;}
	.alert-box{width:800px;height:600px;background:#fff;border-radius: 10px;}
	.uni-table-tr input{font-weight:400;font-size:14px;text-align: center;}
	.uni-table-tr th{background:#f8f8f8;}
	.file-picker__box-content,.uni-easyinput__content-input{background:#f9f9f9;} 
	.uni-forms-item__label{width:120px;}
	uni-textarea {
	    width: 300px;
	    height: 50px; 
	    display: block;
	    position: relative;
	    font-size: 16px;
	    line-height: normal;
	    white-space: pre-wrap;
	    word-break: break-all;
	}
</style>
<style scoped>
	.param-del-icon{width:30px;height:30px;text-align: center;right:-10px;top:-10px;background:#eee;border-radius: 50%;line-height:30px;cursor:pointer;}
	.param-td label{padding:5px 20px;background:#f8f8f8;border:1px solid #eee;border-radius: 5px;color:#666;}
	.param-fuwenben textarea{border:none;background:none;}
	.param-trss{width:100%;border:1px solid #eee;}
	.param-more-add{width:50%;line-height:35px;height:35px;margin-top:20px;margin-left:20%;background:#2979ff;text-align:center;color:#fff;border-radius: 5px;cursor:pointer;}
	.param-input input{line-height:35px;height:35px;font-size:12px;padding-left:5px;}
	.param-input{width:18%;height:35px;line-height:35px;border:1px solid #eee;border-radius: 5px;margin-left:1%;margin-top:10px;margin-right:1%;}
	.param-titles{width:100px;height:35px;font-size:12px;line-height:35px;margin-left:20px;margin-top:10px;background:#2979ff;text-align:center;color:#fff;border-radius: 5px;cursor:pointer;}
	.param-fuwenben{width:100%;min-height:60px;padding-bottom:10px;}
	.param-td input{width:100%;height:40px;line-height:40px;font-size:14px;}
	.param-trs{width:100%;height:40px;border-bottom:1px solid #eee;}
	.param-td{width:calc(20% - 1px);line-height:40px;border-right:1px solid #eee;text-align:center;}
	.param-tr{width:100%;height:40px;background:#f8f8f8;}
	.param-boxs{width:100%;min-height:100px;}
	.alert-proress{width:100%;height:10px;margin-top:20px;}
	.alert-button{width:60%;margin-left:20%;height:40px;background:#00c296;color:#fff;margin-top:30px;line-height:40px;border-radius: 5px;text-align: center;cursor:pointer;}
	.alert-content-item label text{float:left;width:100%;line-height:20px;margin-top:5px;font-size:15px;}
	.alert-label2{width:200px;height:50px;float:left;margin-top:12px;}
	.alert-label1{float:left;margin:15px;width:50px;height:50px;margin-top:25px;}
	.alert-content-item{width:60%;height:80px;margin-left:20%;background:#f8f8f8;border:1px solid #eee;border-radius: 5px;margin-top:20px;}
	.alert-content{width:100%;height:350px;margin-top:20px;}
	.alert-title label:last-child{float:right;margin-right:20px;margin-top:2px;} 
	.alert-title label:first-child{margin-left:20px;}
	.alert-title{width:100%;line-height:40px;border-bottom:1px solid #eee;font-size:14px;}
	.add-param-text{width:100%;line-height:30px;text-align: center;color:#aaa;margin-bottom:20px;}
	.add-param-box{width:15%;margin-left:42.5%;line-height:35px;height:35px;border:1px solid #00c296;color:#00c296;background:#f8f8f8;border-radius: 20px;margin-top:20px;margin-bottom:20px;margin-left:35%;text-align: center;cursor:pointer;}
	.param-box{width:100%;min-height:100px;border-radius: 5px;background:#f8f8f8;}
	.goods-poster div:first-child{margin-top:100px;cursor:pointer;}
	.goods-poster div{font-size:14px;line-height:30px;text-align: center;color:#999;}
	.goods-poster{width:100%;height:270px;border:1px solid #eee;border-radius: 5px;background:#f9f9f9;}
	textarea{width:calc(100% - 20px);min-height:100px;border:1px solid #eee;border-radius: 5px;padding:10px;background:#f9f9f9;font-size:13px;}
	.form-quxiao-submit{width:100px;line-height:40px;height:40px;color:#666;border-radius: 5px;text-align: center;border:1px solid #ccc;margin-right:20px;cursor:pointer;}
	.form-submit{width:100px;line-height:40px;height:40px;background:#2979ff;color:#fff;border-radius: 5px;text-align: center;margin-right:20px;cursor:pointer;}
	.example {
			padding: 15px;
			background-color: #fff;
		}
	
		.segmented-control {
			margin-bottom: 15px;
		}
	
		.button-group {
			margin-top: 15px;
			display: flex;
			justify-content: space-around;
		}
	
		.form-item {
			display: flex;
			align-items: center;
		}
	
		.button {
			display: flex;
			align-items: center;
			height: 35px;
			margin-left: 10px;
		}
	.add-box{width:80%;margin-left:10%;margin-top:30px;min-height:400px;}
</style>

<script>
	var db = uniCloud.database();
	var systemMenu = uniCloud.importObject('systemmenu',{customUI:true});
	var gongshu = uniCloud.importObject('gongshu',{customUI:true});
	import common from '/static/js/common.js';
	export default {
		name:"system-menu-add",
		data() {
			return {
				spec:'',//中文规格参数
				en_spec:'',//英文规格参数
				describe:'',//中文技术说明
				en_describe:'',//英文技术说明
				currentLabelItem:{},//当前选中的label
				currentLabelIndex:{
					index:null,
					indexs:null
				},//当前选中的index
				deliveryTime: [
					{
						text:'24小时内',
						value:'within 24 hours'
					},
					{
						text:'48小时内',
						value:'within 48 hours'
					},
					{
						text:'一周内',
						value:'within a week'
					},
					{
						text:'两周内',
						value:'within two week'
					},
					{
						text:'一月内',
						value:'within one month'
					}
				],//发货日期
				categoryVal:[],//分类数据
				paramIndex:null,//当前选中的param的index
				param:[
					{
						model:'',
						en_model:'',
						spec:'',
						en_spec:'',
						price:null,
						en_price:null,
						delivery_time:'within 48 hours',
						en_delivery_time:'48小时内',
						zh_pdf:{
							title:'',
							url:''
						},
						en_pdf:{
							title:'',
							url:''
						},
						zh_3d:{
							title:'',
							url:''
						},
						en_3d:{
							title:'',
							url:''
						},
						item:[],
						en_item:[],
						children:''
					}
				],
				category:[],//分类
				percent:0,//上传进度
				zhpdfPercent:0,//pdf文档上传进度
				enpdfPercent:0,//pdf文档上传进度
				zhstepPercent:0,//3d文档上传进度
				enstepPercent:0,//3d文档上传进度
				parentTitle:null,
				uploadItem:'',
				image:[],//图片
				feature:'',//特色
				formData:{
					title:'',//商品标题
					en_title:'',//英文标题
					category:[],//分类
					category_id:[],//分了id
					content:'',//介绍
					en_content:'',//英文介绍
					poster:'',//封面
					en_poster:'',//英文封面
					images:[],//主图
					en_images:[],//英文主图
					feature:[],//商品特色
					en_feature:[],//英文特色
					spec:'',//参数规格
					en_spec:'',//英文参数规格
					describe:'',//技术说明
					en_describe:'',//英文技术说明
					describe_image:'',//使用说明图中文
					en_describe_image:'',//英文使用说明图
					example_image:'',//应用举例图
					en_example_image:'',//应用举例图英文
					param:[],//sku参数
					is_shelf:true,
					userinfo:{},//登录用户信息
				},
				routes: [
				        {
				          to: "/A",
				          name: "商品管理",
				        },
				        {
				          to: "/B",
				          name: "商品编辑",
				        }
				      ]
			};
		},
		props:{
			id:{
				type:String
			},
			children:{
				type:String
			},
			childrenId:{
				type:String
			},
			newAdd:{
				type:String
			},
			userinfo:{
				type:Object
			}
		},
		mounted() {
				var that = this;
				//查询出产品分类
				that.getCategory();
				if(this.id && this.id!='undefined' && !this.newAdd){
					// uni.showLoading({
					// 	title:'加载中'
					// });
					
					//查询出默认值
					that.getDefaultData();
				}
				
				// 需要在onReady中设置规则
				this.$refs.form.setRules(this.rules)
				//查询出当前记录
				
			},
		methods:{
			//上传主图
			uploadParamImage(index){
				var that = this;
				
				uni.chooseImage({
					success: (chooseImageRes) => {
						uni.showLoading({
							title:'上传中'
						})
						const tempFilePaths = chooseImageRes.tempFilePaths[0];
						var tempFiles = chooseImageRes.tempFiles[0];
						var fileName = common.generateUUIDWithExtension(tempFiles.name);
						uniCloud.uploadFile({
						        filePath: tempFilePaths,
						        cloudPath: fileName,
						        onUploadProgress: function(progressEvent) {
						          console.log(progressEvent);
						          var percentCompleted = Math.round(
						            (progressEvent.loaded * 100) / progressEvent.total
						          );
						        },
						        success(e) {
									uni.hideLoading()
									that.param[index].image = e.fileID;
								},
								fail() {
									uni.hideLoading()
								}
						      });
					}
				});
			},
			//删除一项
			delParam(index){
				this.param.splice(index,1);
			},
			//增加一项
			addParam(){
				this.param.push({
						model:'',
						spec:'',
						price:null,
						delivery_time:'within 48 hours',
						zh_pdf:{
							title:'',
							url:''
						},
						en_pdf:{
							title:'',
							url:''
						},
						zh_3d:{
							title:'',
							url:''
						},
						en_3d:{
							title:'',
							url:''
						},
						item:'',
						children:''
					});
			},
			
			//设置周期属性
			setLabel(item,index,indexs){
				this.currentLabelItem = item;
				this.currentLabelIndex = {
					index:index,
					indexs:indexs
				}
			},
			//根据id查询出默认值
			getDefaultData(){
				var that = this;
				var id = this.id;
				db.collection('goods').where({_id:id}).get({getOne:true}).then(res=>{
					var data = res.result.data;
					this.spec = data.spec;
					this.en_spec = data.en_spec;
					this.describe = data.describe;
					this.en_describe = data.en_describe;
					//处理数据
					var res = {
						title:data.title+'|'+data.en_title,
						content:data.content+'|'+data.en_content,
					}
					var feature = data.feature;
					var en_Feature = data.en_feature;
					var featureVal = '';
					//商品特色
					for(var i = 0;i < feature.length;i++){
						var zhFeature = feature[i];
						var enFeature = en_Feature[i];
						featureVal += '@'+zhFeature+'|'+enFeature;
					}
					that.feature = featureVal.substring(1,20000);
					res.poster = data.poster;
					res.en_poster = data.en_poster;
					res.images = data.images;
					res.en_images = data.en_images;
					res.spec = data.spec;
					res.en_spec = data.en_spec;
					res.describe = data.describe;
					res.en_describe = data.en_describe;
					res.describe_image = data.describe_image;
					res.en_describe_image = data.en_describe_image;
					res.example_image = data.example_image;
					res.en_example_image = data.en_example_image;
					res.step_file = data.step_file;
					var param = data.param;
					for(var i = 0;i<param.length;i++){
						var model = param[i].model;
						param[i].model = model;
						var spec = param[i].spec + '|'+ param[i].en_spec;
						param[i].spec = spec;
						var price = param[i].price + '|' + param[i].en_price;
						param[i].price = price;
						if(this.isJsonObject(param[i].zh_pdf) == false){
							param[i].zh_pdf = {
								title:'',
								url:''
							}
						}
						
						if(this.isJsonObject(param[i].en_pdf) == false){
							param[i].en_pdf = {
								title:'',
								url:''
							}
						}
						
						
						if(this.isJsonObject(param[i].zh_3d) == false){
							param[i].zh_3d = {
								title:'',
								url:''
							}
						}
						
						
						if(this.isJsonObject(param[i].en_3d) == false){
							param[i].en_3d = {
								title:'',
								url:''
							}
						}
						
						
					}
					this.param = param;
					that.formData = res;
					that.categoryVal = data.category_id[data.category_id.length - 1];
				});
			},
			isJsonObject(value) {
			  // 排除null和非对象类型
			  if (value === null || typeof value !== 'object') {
			    return false;
			  }
			  
			  // 检查对象的构造函数是否为Object
			  // 排除数组、日期、正则等特殊对象
			  return value.constructor === Object;
			},
			//关闭上传手册弹窗
			colseManual(){
				this.$refs.manualPopup.close();
			},
			//内容变化以后
			onchangeCategory(val) {
			    var value = val.detail.value;
			    
			    // 初始化数组（关键修复：确保数组已存在）
			    if (!this.formData.category) {
			        this.formData.category = [];
			    }
			    if (!this.formData.category_id) {
			        this.formData.category_id = [];
			    }
			    
			    // 先清空数组，避免重复添加
			    this.formData.category = [];
			    this.formData.category_id = [];
			    
			    for(var i = 0; i < value.length; i++){
			        this.formData.category.push(value[i].text);
			        this.formData.category_id.push(value[i].value);
			    }
			},
			//获取分类
			getCategory(){
				db.collection('category').where({is_show:true}).field('_id as value,title as text,children').orderBy('sort asc').get().then(res=>{
					var category = res.result.data;
					for(var i = 0;i<category.length;i++){
						var children = category[i].children;
						if(children && children[0]){
							for(var x = 0;x < children.length;x++){
								var value = children[x]._id;
								var text = children[x].title;
								category[i].children[x] = {
									value:value,
									text:text
								}
							}
						}
						
					}
					this.category = category;
				});
			},
			//上传文件
			uploadFile(item,index){
				var that = this;
				
					if(item == 'zhpdf' || item =='enpdf'){
						var extension = ['.pdf'];
					}else if(item == 'zh3d' || item =='en3d'){
						var extension = ['.step','.igs','x_t','x_b'];
					}
					uni.chooseFile({
					  count: 1,
					  extension:extension,
					  success(res) {
						  uni.showLoading({
						  	title:'上传中'
						  })
						  var tempFiles = res.tempFiles[0];
						  var title = tempFiles.name;
						  var filePath = res.tempFilePaths[0];
						 var size = tempFiles.size;
						  var fileName = common.generateUUIDWithExtension(tempFiles.name);
						  uniCloud.uploadFile({
						          filePath: filePath,
						          cloudPath: fileName,
						          onUploadProgress: function(progressEvent) {
						            var percentCompleted = Math.round(
						              (progressEvent.loaded * 100) / progressEvent.total
						            );
						  		  
						  		  that.uploadItem = item;
								  if(item == 'zhpdf'){
									  that.zhpdfPercent = percentCompleted;
								  }else if(item =='enpdf'){
									  that.enpdfPercent = percentCompleted;
								  }else if(item == 'zh3d'){
									  that.zhstepPercent = percentCompleted;
								  }else if(item == 'en3d'){
									  that.enstepPercent = percentCompleted;
								  }
						          },
						          success(res) {
						  			var filePath = res.fileID;
										if(item == 'zhpdf'){
											that.param[index]['zh_pdf'].title = title;
												that.param[index]['zh_pdf'].url = filePath;
										}else if(item == 'enpdf'){
											that.param[index]['en_pdf'].title = title;
											that.param[index]['en_pdf'].url = filePath;
										}else if(item == 'zh3d'){
											that.param[index]['zh_3d'].title = title;
												that.param[index]['zh_3d'].url = filePath;
											}else if(item =='en3d'){
												that.param[index]['en_3d'].title = title;
												that.param[index]['en_3d'].url = filePath;
											}
											
									uni.hideLoading();
						  		}
						        });
					}
					})
				},
			//弹出上传手册弹窗
			alertUploadManual(index){
				this.paramIndex = index;
				this.$refs.manualPopup.open();
			},
			//获取中文技术说明
			getZhDescribe(e){
				this.formData.describe = e;
			},
			//获取英文技术说明
			getEnDescribe(e){
				this.formData.en_describe = e;
			},
			//获取中文参数规格内容
			getZhSpec(e){
				this.formData.spec = e;
			},
			//获取英文参数规格内容
			getEnSpec(e){
				this.formData.en_spec = e;
			},
			//上传封面
		  uploadPoster(item){
				var that = this;
				that.percent = 0;
				uni.chooseImage({
				  count: 1,
				  success(res) {
					  var tempFiles = res.tempFiles[0];
					 var size = tempFiles.size;
					  var fileName = common.generateUUIDWithExtension(tempFiles.name);
					  if(item == 'zh'){
						  var uploadItem = 'poster';
					  }else if(item == 'en'){
						  var uploadItem = 'en_poster';
					  }
					  that.uploadImage(tempFiles.path,fileName,uploadItem);
				}
				})
			},
			//上传图片
			async uploadImage(path,fileName,item){
				var that = this;
				var imageInfo = await this.getImageInfo(path);
				if(imageInfo.width != 1920 || imageInfo.height != 540){
					uni.showToast({
						title:'图片尺寸必须为1920px * 540px,类型为jpg/webp',
						icon:'none',
						duration:3000
					})
					return false;
				}
				
				uniCloud.uploadFile({
				        filePath: path,
				        cloudPath: fileName,
				        onUploadProgress: function(progressEvent) {
				          var percentCompleted = Math.round(
				            (progressEvent.loaded * 100) / progressEvent.total
				          );
						  
						  that.percent = percentCompleted;
						  that.uploadItem = item;
				        },
				        success(res) {
							var filePath = res.fileID;
							if(item == 'poster'){
									that.formData.poster = filePath;
							}else if(item == 'en_poster'){
									that.formData.en_poster = filePath;
								}
						}
				      });

			},
			//获取图片基本信息
			getImageInfo(imagePath) {
			  return new Promise((resolve, reject) => {
			    // 检查参数有效性
			    if (!imagePath || typeof imagePath !== 'string') {
			      return reject(new Error('请提供有效的图片路径'));
			    }
			    
			    uni.getImageInfo({
			      src: imagePath,
			      success: (res) => {
			        // 成功获取图片信息
			        resolve({
			          width: res.width,
			          height: res.height,
			          path: res.path,
			          type: res.type,
			          orientation: res.orientation || '',
			          size: res.size || 0
			        });
			      },
			      fail: (err) => {
			        // 获取失败，返回错误信息
			        console.error('[getImageDetails] 失败:', err);
			        reject(new Error(`获取图片信息失败: ${err.errMsg || '未知错误'}`));
			      }
			    });
			  });
			},
			
			//删除属性选项
			delParam(e){
				this.param.splice(e,1);
			},
			//跳转列表页
			navigatorToList(){
				uni.navigateTo({
					url:'/pages/index/index?page=goods-list'
				})
			},

			//设置显示开关
			setIsshow(event){
				this.formData.is_shelf = event.detail.value;
			},
			isPositiveNumber(value) {
			  // 先转换为数字
			  const num = Number(value);
			  // 判断是否为有效数字且大于0
			  return !isNaN(num) && num > 0;
			},
			//移除所有的空格，换行符和制表符
			cleanString(str) {
			  if (!str || typeof str !== 'string') return '';
			  
			  // 1. 移除所有HTML标签（包括<n>标签）
			  let cleaned = str.replace(/<[^>]*>/g, '');
			  
			  // 2. 移除所有空白字符（空格、制表符、换行符等）
			  cleaned = cleaned.replace(/\s+/g, '');
			  
			  return cleaned;
			},
			//提交订单
			submitForm(form){
				var that = this;
				this.$refs.form.validate().then(res=>{
					res.category = that.formData.category;
					res.param = [];
					res.category_id = that.formData.category_id;
					res.step_file = that.formData.step_file;
					var title = res.title.split('|');
					res.title = title[0];
					res.en_title = title[1];
					var content = res.content.split('|');
					res.content = content[0];
					res.en_content = content[1];
					var feature = that.feature.split('@');
					res.feature = [];
					res.en_feature = [];
					var param = that.param;
					for(var i = 0;i < feature.length;i ++){
						var itemArray = feature[i].split('|');
						res.feature.push(this.cleanString(itemArray[0]));
						res.en_feature.push(this.cleanString(itemArray[1]));
					}
					if(!res.title){
						uni.showToast({
							title:'请输入中文标题',
							icon:'none',
							duration:2000
						})
						return false;
					}
					if(!res.en_title){
						uni.showToast({
							title:'请输入英文标题',
							icon:'none',
							duration:2000
						})
						return false;
					}
					
					if(!res.content){
						uni.showToast({
							title:'请输中文介绍',
							icon:'none',
							duration:2000
						})
						return false;
					}
					if(!res.en_content){
						uni.showToast({
							title:'请输英文介绍',
							icon:'none',
							duration:2000
						})
						return false;
					}
					
					if(!res.poster){
						uni.showToast({
							title:'请上传中文封面',
							icon:'none',
							duration:2000
						})
						return false;
					}
					
					
					if(!res.en_poster){
						uni.showToast({
							title:'请上传英文封面',
							icon:'none',
							duration:2000
						})
						return false;
					}
					
					if(res.images.length < 1){
						uni.showToast({
							title:'请上传中文主图',
							icon:'none',
							duration:2000
						})
						return false;
					}
					
					
					if(res.en_images.length < 1){
						uni.showToast({
							title:'请上传英文主图',
							icon:'none',
							duration:2000
						})
						return false;
					}
					
					//处理规格参数
					for(var i = 0;i<param.length;i++){
						var children = param[i].children;
						//处理模型
						var model = param[i].model;
						param[i].en_model = model;
						//处理规格
						var spec = param[i].spec;
						var specArray = spec.split('|');
						param[i].spec = specArray[0];
						param[i].en_spec = specArray[1];
						//处理价格
						var price = param[i].price;
						var priceArray = price.split('|');
						param[i].price = priceArray[0];
						if(!this.isPositiveNumber(param[i].price)){
							uni.showToast({
								title:'价格必须为正数',
								icon:'none'
							})
							return false;
						}
						param[i].en_price = priceArray[1];
						
						if(!this.isPositiveNumber(param[i].en_price)){
							uni.showToast({
								title:'价格必须为正数',
								icon:'none'
							})
							return false;
						}
						
						param[i].number = 1;
						//处理配送时间
						var deliveryTime = param[i].en_delivery_time;
						if(deliveryTime && this.deliveryTime){
							param[i].en_delivery_time = deliveryTime;
							const index = this.deliveryTime.findIndex(item => item.value == deliveryTime);
							param[i].delivery_time = this.deliveryTime[index].text;
						}
						var item = children.split('#');
						var zhItem = [];
						var enItem = [];
						for(var x = 0;x<item.length;x++){
							var items = item[x].split('@');
							zhItem.push(items[0]);
							enItem.push(items[1]);
						}
						
						this.param[i].item = zhItem;
						this.param[i].en_item = enItem;
					}
					res.param = param;
					//登录用户
					res.create_uid = that.userinfo._id;
					var id = this.id;
					uni.showLoading({
						title:'保存中'
					})
						db.collection('goods').where({_id:id}).update(res).then(result=>{
								uni.hideLoading()
								uni.showToast({
									title:'修改成功',
									icon:'none',
									duration:2000
								})
								setTimeout(function(){
									uni.redirectTo({
										url:'/pages/index/index?page=goods-list'
									})
								},2000)
								
						}).catch(err=>{
							console.log('err',err);
						});
						
					
					
				}).catch(err =>{
					console.log('表单错误信息：', err);
				})
			}
		}
	}
</script>

